package com.hww.slow_sql;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

/**
 * 针对全局的mapper进行aop增强, 做慢SQL记录
 *
 * @author xiaojie
 * @date 2021/1/8 11:11 下午
 */
@Slf4j
@Component
public class SqlSessionBeanPostProcessor implements BeanPostProcessor {

    /**
     * 慢SQL配置文件
     */
    @Autowired
    private SlowSQLConfig slowSQLConfig;

    /**
     * 慢SQL处理器
     */
    @Autowired
    private SlowSQLProcessor slowSQLProcessor;

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {
        if (bean instanceof SqlSessionFactory) {
            initMybatis(bean);
        }
        if (bean instanceof SqlSessionTemplate) {
            initMybatis(((SqlSessionTemplate) bean).getSqlSessionFactory());
        }
        return bean;
    }

    /**
     * 初始化mybatis
     *
     * @param bean
     */
    protected void initMybatis(Object bean) {
        log.error("开始初始化慢SQL拦截器.");
        SqlSessionFactory sessionFactory = (SqlSessionFactory) bean;
        sessionFactory.getConfiguration().addInterceptor(new SlowSQLInterceptor(this.slowSQLConfig, this.slowSQLProcessor));
        log.error("慢SQL拦截器初始化完毕, 慢SQL时间设定[{}]秒.", this.slowSQLConfig.getSlowSqlTime());
    }
}
